<template>
  <div class="dept-select-list-wrap">
    <div :class="{'dept-wrap': !onlyShowUser, 'dept-wrap-onlyShowUser': onlyShowUser}">
      <template v-if="!onlyShowUser">
        <div class="bread-crumb-wrap">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, index) in modBreadcrumbData" :key="index">
              <span :class="{'active': index + 1 === modBreadcrumbData.length }" class="bread-crumb-item" @click="crumbClick(index)">{{ item.departmentName }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <el-checkbox v-if="targetDept.length > 0" :value="isAllChecked" style="padding-left: 24px" @change="checkAllFun">全选</el-checkbox>
        <empty-state v-if="targetDept.length === 0" height="365px" text="暂无角色" dec="管理员还没有设置角色" />
      </template>
      <template v-for="(item, index) in targetDept">
        <dept-select-item v-if="item.isDepartment === 1" :key="index" :is-active="isChecked(item.id)" :dept-info="item" @check="targetCheck($event, 'id')" @click="deptSelected" />
        <staff-select-item v-else :key="index" :is-active="isChecked(item.userId)" :info="item" @check="targetCheck($event, 'userId')" />
      </template>
    </div>
  </div>
</template>
<script>
import DeptSelectItem from './deptSelectItem';
import StaffSelectItem from './staffSelectItem';
import { dfsDept } from './utils.js';
import EmptyState from './emptyState';
export default {
  name: 'DeptSelectList',
  components: {
    DeptSelectItem,
    StaffSelectItem,
    EmptyState
  },
  props: {
    breadcrumbData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    selectItems: {
      type: Array,
      default: () => {
        return [];
      }
    },
    selectUsers: {
      type: Array,
      default: () => {
        return [];
      }
    },
    max: {
      type: Number,
      default: 50
    },
    onlyShowUser: { // 是否只展示用户（用于在第一页展示 自定义选择人员的初始值）
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      modBreadcrumbData: null
    };
  },
  computed: {
    // 判断是否全选
    isAllChecked() {
      const total = this.targetDept.length;
      let currentTime = 0; // 出现次数
      this.targetDept.forEach(item => {
        const { userId, id } = item;
        if (item.isDepartment) {
          if (this.selectItemIds.indexOf(id) >= 0) currentTime++;
        } else {
          if (userId) {
            if (this.selectItemIds.indexOf(userId) >= 0) currentTime++;
          } else {
            if (this.selectItemIds.indexOf(id) >= 0) currentTime++;
          }
        }
      });
      return currentTime === total;
    },
    targetDept() {
      const lastIndex = this.modBreadcrumbData.length - 1;
      const lastDept = this.modBreadcrumbData[lastIndex];
      if (lastDept && lastDept.children) {
        return lastDept.children;
      } else {
        return [];
      }
    },
    auditorIds() {
      const temp = this.selectUsers.map(item => item.id);
      return temp;
    },
    selectItemIds() {
      if (this.selectItems.length > 0) {
        const temp = [];
        this.selectItems.forEach(item => {
          if (item.hasOwnProperty('isDepartment') || item.hasOwnProperty('isRole')) { // 有isDepartment 证明是通过部门列表获取的值
            if (item.isDepartment) {
              temp.push(item.id);
            } else {
              temp.push(item.userId);
            }
          } else {
            temp.push(item.id);
          }
        });
        return temp;
      } else {
        return [];
      }
    }
  },
  watch: {
    breadcrumbData: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          this.modBreadcrumbData = JSON.parse(JSON.stringify(newVal));
        }
      },
      immediate: true
    }
  },
  methods: {
    // 判断复选框是否选中
    isChecked(id) {
      return this.selectItemIds.indexOf(id) >= 0;
    },
    // 部门下级点击
    deptSelected(item) {
      this.modBreadcrumbData.push(item);
    },
    // 全选逻辑
    checkAllFun(val) {
      let peopleNum = 0;
      this.targetDept.forEach(item => {
        if (item.isDepartment) {
          peopleNum += item.peopleNum;
        } else {
          peopleNum += 1;
        }
      });
      if (peopleNum + this.auditorIds.length > this.max) {
        this.$message({
          type: 'warning',
          message: '选择超过限制'
        });
        return;
      }
      this.targetDept.forEach(item => {
        const param = { item, isChecked: val };
        setTimeout(() => {
          if (item.isDepartment) {
            if (val) {
              if (this.selectItemIds.indexOf(item.id) < 0) {
                this.targetCheck(param, 'id');
              }
            } else {
              this.targetCheck(param, 'id');
            }
          } else {
            if (val) {
              if (this.selectItemIds.indexOf(item.userId) < 0) {
                this.targetCheck(param, 'userId');
              }
            } else {
              this.targetCheck(param, 'userId');
            }
          }
        }, 0);
      });
    },
    // 部门或员工的复选框点击
    targetCheck(data, field) {
      try {
        const isCheck = data.isChecked;
        const item = data.item;
        const tempSelectItemIds = JSON.parse(JSON.stringify(this.selectItemIds));
        const tempSelectItems = JSON.parse(JSON.stringify(this.selectItems));
        if (isCheck) {
          if (item.isDepartment) {
            const peopleNum = item.peopleNum ? item.peopleNum : 0;
            if (this.selectUsers.length + peopleNum >= this.max) {
              this.$message({
                type: 'warning',
                message: '选择超过限制'
              });
              return;
            }
          } else {
            if (this.selectUsers.length >= this.max) {
              this.$message({
                type: 'warning',
                message: '选择超过限制'
              });
              return;
            }
          }
          tempSelectItems.push(item);
          this.$emit('update:selectItems', tempSelectItems);
          this.settleStaff(item);
        } else {
          const curIndex = tempSelectItemIds.indexOf(item[field]);
          if (curIndex >= 0) {
            tempSelectItems.splice(curIndex, 1);
            this.$emit('update:selectItems', tempSelectItems);
          }
          this.deleteStaff(item);
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 当选择后 整理部门下的员工并返回
    settleStaff(item) {
      const { userId, userName, avatar, post, number } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectUsers));
      if (item.isDepartment) {
        const staffs = dfsDept(item, []);
        staffs.forEach(item => {
          tempSelectUsers.push(item);
        });
        // tempSelectUsers = this.arrRepeat(tempSelectUsers);
        this.$emit('update:selectUsers', tempSelectUsers);
      } else {
        const param = {
          id: userId,
          userName,
          avatar,
          post,
          number
        };
        tempSelectUsers.push(param);
        this.$emit('update:selectUsers', tempSelectUsers);
      }
    },
    // 取消选择后 审批人选择列表 删除 该部门下人员
    deleteStaff(item) {
      const { userId } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectUsers));
      if (item.isDepartment) {
        const staffs = dfsDept(item, []);
        while (staffs.length) {
          const cur = staffs.pop();
          const selectUserIds = tempSelectUsers.map(item => item.id);
          const deleteIndex = selectUserIds.indexOf(cur.id);
          if (deleteIndex >= 0) {
            tempSelectUsers.splice(deleteIndex, 1);
          }
        }
        this.$emit('update:selectUsers', tempSelectUsers);
      } else {
        const selectUserIds = tempSelectUsers.map(item => item.id);
        const deleteIndex = selectUserIds.indexOf(userId);
        if (deleteIndex >= 0) {
          tempSelectUsers.splice(deleteIndex, 1);
          this.$emit('update:selectUsers', tempSelectUsers);
        }
      }
    },
    // 面包屑点击
    crumbClick(index) {
      if (index === this.modBreadcrumbData.length - 1) return;
      this.modBreadcrumbData = this.modBreadcrumbData.slice(0, index + 1);
    }
  }
};
</script>
<style lang="scss" scoped>
@import url('./common.scss');
.bread-crumb-wrap {
  & ::v-deep {
    .el-breadcrumb {
      line-height: 1.5 !important;
    }
    .el-breadcrumb__item {
      float: none !important;
    }
  }
}
.dept-wrap-onlyShowUser {
  .staff-select-item-wrap {
    padding-left: 5px !important;
  }
}
.dept-wrap {
  height: 422px;
  @include scrollBar($width: 4px);
}
.bread-crumb-item {
  cursor: pointer;
  font-size: 14px;
  color: #333;
  &.active {
    cursor: not-allowed;
    color: #999
  }
}
</style>
